package main

import (
	"golang-tutorial/go-frameworks-and-tools/go-kit/go-kit-server/Services"
	"golang-tutorial/go-frameworks-and-tools/go-kit/go-kit-server/util"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	httpstransport "github.com/go-kit/kit/transport/http"
	mymux "github.com/gorilla/mux"
)

func main() {

	fmt.Println("server start")
	user := Services.UserService{}
	endp := Services.GenUserEndpoint(user)
	serverHandler := httpstransport.NewServer(endp, Services.DocodeUserRequest, Services.EncodeUserResponse)

	router := mymux.NewRouter()
	{
		router.Methods("GET", "DELETE").Path(`/user/{uid:\d+}`).Handler(serverHandler)
		router.Methods("GET").Path("/health").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			writer.Header().Set("Content-type", "application/json")
			writer.Write([]byte(`{"status":"ok"}`))
		})
	}
	errChan := make(chan error)
	go (func() {
		util.RegService() //注册服务
		err := http.ListenAndServe(":8081", router)
		if err != nil {
			log.Panicln(err)
			errChan <- err
		}
  })()
  
	//信号监听
	go (func() {
		sig_c := make(chan os.Signal)
		signal.Notify(sig_c, syscall.SIGINT, syscall.SIGTERM)
		errChan <-fmt.Errorf("%s", <-sig_c)
	})()
  
  getErr := <-errChan
  util.Unregservice()
  log.Println(getErr)
}
